package com.stu.day16.Demo2;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

/**
 *
 * @author zy
 * @date 2025/2/14 10:55
 */
public class BaseDaoImpl<T> implements IBaseDao<T>{
    private final static String path = "src/com/stu/day16/data/xxx.txt";

    @Override
    public void add(T t) {
        List<T> list = findAll();  // 拿出文件内容到list
        if(!list.isEmpty()){
            list.removeIf(new Predicate<T>() {  // 与新加入对象一样时,删除list中已有的对象
                @Override
                public boolean test(T t2) {
                    if(t2.equals(t))
                        return true;
                    return false;
                }
            });
        }

        list.add(t);  // 加入到list

        try(ObjectOutputStream oop = new ObjectOutputStream(new FileOutputStream(path))){
            oop.writeObject(list);  // list写入文件,同时清空文件中的不符合要求内容
            System.out.println(t+"加入成功");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<T> findAll() {
        List<T> list = new ArrayList();
        try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path))){
            list = (List<T>)ois.readObject();

        } catch (FileNotFoundException e) {  // 文件不存在
//            throw new RuntimeException(e);
            list.clear();  // 清空list
        } catch (IOException e) {
            //java.io.EOFException 到达文件的末尾,没有有效的数据流让我们读取,比如文件为空
            //java.io.StreamCorruptedException-文件的内容和接受的类型不匹配 - 无效的数据-invalid stream header:
//            throw new RuntimeException(e);
            list.clear();  // 清空list
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    @Override
    public void delById(Serializable t) {

    }
}
